import type { Effect, Reducer } from '@umijs/max';

export interface UserModelState {
  currentUserInfo: Partial<HOMEAPI.CurrentUser>;
  isShowLoginModal: boolean;
  isRegisterModal: boolean;
}

export interface UserModelType {
  namespace: 'usermodel';
  state: UserModelState;
  effects: {
    query?: Effect;
  };
  reducers: {
    saveCurrentUserInfo: Reducer<UserModelState>;
    // 启用 immer 之后
    // save: ImmerReducer<UserModelState>;
    changeIsShowLoginModal: Reducer<UserModelState>;
    changeIsRegisterModal: Reducer<UserModelState>;
  };
  // subscriptions: { setup: Subscription };
}

const UserModel: UserModelType = {
  namespace: 'usermodel',
  state: {
    currentUserInfo: {
      username: '',
    },
    isShowLoginModal: false,
    isRegisterModal: false,
  },

  effects: {
    // *query({ payload }, { call, put }) {},
  },
  reducers: {
    saveCurrentUserInfo(state, action) {
      const { payload } = action;
      // 将用户信息持久化到本地
      if (payload) {
        localStorage.setItem('blogUserInfo', JSON.stringify(payload));
      }
      return {
        ...state,
        currentUserInfo: payload,
      };
    },
    changeIsShowLoginModal(state, action) {
      const { payload } = action;
      return {
        ...state,
        isShowLoginModal: payload,
      };
    },
    changeIsRegisterModal(state, action) {
      const { payload } = action;
      console.log(payload);

      return {
        ...state,
        isRegisterModal: payload,
      };
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
};

export default UserModel;
